/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.oss.impl;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.moon.framework.autoconfigure.oss.OssService;
import org.moon.framework.autoconfigure.oss.domain.MoonFile;
import org.moon.framework.autoconfigure.oss.props.OssProperties;
import org.moon.framework.autoconfigure.oss.utils.OssUtils;
import org.moon.framework.autoconfigure.utils.Func;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.LocalDate;
import java.util.List;

/**
 * 文件存放本地 nginx
 * @author moon
 */
@Slf4j
public class LocalOssProviderImpl implements OssService {

	private OssProperties ossProperties;

	public LocalOssProviderImpl(OssProperties ossProperties){
		this.ossProperties = ossProperties;
	}

	@Override
	public MoonFile putFile(MultipartFile file) {
		return putFile(OssUtils.getFileName(file.getOriginalFilename()),file);
	}

	@Override
	public MoonFile putFile(String fileName, MultipartFile file) {
		String bucketName = OssUtils.getBucketName(ossProperties.getBucketName());
		LocalDate date = LocalDate.now();
		String remoteFileDir = bucketName + "/" + date.getYear() + "/" + date.getMonthValue() + "/" + date.getDayOfMonth();
		try {
			File dir = new File(remoteFileDir);
			if(!dir.exists()){
				FileUtils.forceMkdir(new File(remoteFileDir));
			}
			FileUtils.copyInputStreamToFile(file.getInputStream(),new File(remoteFileDir+"/"+fileName));
			if(!Func.isWinOs()){
				Runtime.getRuntime().exec("chmod -R 755 "+remoteFileDir);
			}
			MoonFile moonFile = MoonFile.builder().originalName(fileName).name(fileName).domain(this.ossProperties.getEndpoint()).link(bucketName.concat("/").concat(fileName)).build();
			return moonFile;
		}catch (Exception e){
			log.error(e.getMessage(),e);
			return null;
		}
	}

	@Override
	public void removeFiles(List<String> fileNames) {
		log.error("scp方式不支持删除...");
	}

	@Override
	public void removeFile(String fileNames) {
		log.error("scp方式不支持删除...");
	}
}